//
//  MBSpaceMyCollectionShowViewController.m
//  MiBaoTu
//
//  Created by admin on 16/9/21.
//  Copyright © 2016年 com.caesartech15. All rights reserved.
//

#import "MBSpaceDowningMusicViewController.h"
#import "MBSpaceAddMusicViewController.h"
#import "MBSongDetailController.h"
#import "MBSongDetailForIController.h"

#import "MBSpaceDowningAllMusicCell.h"
#import "MBSpaceCollectionCompileView.h"
#import "SharePLayerView.h"

#import "MBSongDetailForIpadController.h"
@interface MBSpaceDowningMusicViewController ()<UITableViewDataSource,UITableViewDelegate,MBSpaceCollectionCompileViewDelegate,MBSpaceDowningAllMusicCellDelegate,SharePLayerViewDelegate,DownManagerDelegate> {
    UITableView                             *_tableView;
    MBSpaceCollectionCompileView            *_compileView;
    NSMutableArray                          *_selectMusicArr;//保存选中的歌曲
    NSMutableArray                          *_downingMusicArr; //正在下载的歌曲
    NSMutableArray                          *_stopDowningMusicArr;//已暂停的下载歌曲列表ID
    DownMusicModel                          *_currentMusicModel;//当前选中的歌曲
    MusicPLayType                           _musicPlayType;
    
    BOOL                                    _isShowAllStop; //如果是下载状态就显示全部暂停
    DowningMusicStepType                    _allCellStop; //全部下载或全部开始
}

@property (nonatomic,assign)BOOL isCompiling;//是否批量编译
@property (nonatomic,assign)BOOL isAllSelcting;//是否全选

@end

@implementation MBSpaceDowningMusicViewController

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if (_downingMusicArr.count == 0) {        
        if ([fileManager fileExistsAtPath:[MusicCachesDirectory stringByAppendingPathComponent:@"downingloadDetail.data"]]) {
            [fileManager removeItemAtPath:[MusicCachesDirectory stringByAppendingPathComponent:@"downingloadDetail.data"] error:nil];
        }
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.isCompiling = NO;
    self.isAllSelcting = NO;
    _selectMusicArr = [[NSMutableArray alloc]init];
    _downingMusicArr = [[NSMutableArray alloc]init];
    _stopDowningMusicArr = [[NSMutableArray alloc]init];
    _musicPlayType = MusicPLayType_DowningMusic;
    _isShowAllStop = NO;
    _allCellStop = DowningMusicStepType_defult;
    // Do any additional setup after loading the view.
    [self setNavBar];
    [self onCreateUI];
    
    [self loadData];
}

#pragma mark - Actions
#pragma mark - UI
- (void)setNavBar
{
    [self setTitleView:@"正在下载"];
    
    [self setBackItem];
    
    [self setRightPlayerItem];
}

- (void)onCreateUI
{
    _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, self.view.height) style:UITableViewStylePlain];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.backgroundColor = [UIColor clearColor];
    _tableView.backgroundView = nil;
    [self.view addSubview:_tableView];
    _tableView.tableHeaderView = [self setTableHeaderViewWithIndex:2];
    
    //批量弹出框
    _compileView = [[MBSpaceCollectionCompileView alloc]initWithFrame:CGRectMake(0, SCREEN_HEIGHT, SCREEN_WIDTH, 100*PERCEN) WithIndex:2];
    _compileView.delegate = self;
    _compileView.hidden = YES;
    [self.view addSubview:_compileView];
}

- (void)onUpdateUIForView:(UIDeviceOrientation)orientation
{
    _tableView.frame = CGRectMake(0, 0, SCREEN_WIDTH, self.view.height);
    _tableView.tableHeaderView = [self setTableHeaderViewWithIndex:2];
    _compileView.frame = CGRectMake(0, SCREEN_HEIGHT, SCREEN_WIDTH, 100*PERCEN);
    _compileView.orientation = self.orientation;
    [_tableView reloadData];
}

#pragma mark - 获取数据
- (void)loadData
{
    //之前暂停的
    NSArray *sessionModels = [NSKeyedUnarchiver unarchiveObjectWithFile:DownloadDetailPath];
    if (sessionModels.count > 0) {
        [_stopDowningMusicArr removeAllObjects];
         [_downingMusicArr removeAllObjects];
        for (DownMusicModel *musicModel in sessionModels) {
            NSString *musicID = [NSString stringWithFormat:@"%@",musicModel.musicID];
            [_stopDowningMusicArr addObject:musicID];
        }
        [_downingMusicArr addObjectsFromArray:sessionModels];
    }
    
    //开始下载的
//    NSArray *musicDowningArr = [[DownManager staredInstance]currentDownloads];
//    if (musicDowningArr.count > 0) {
//        for (DownMusicModel *musicModel in musicDowningArr) {
//            NSString *musicID = [NSString stringWithFormat:@"%@",musicModel.musicID];
//            if (![_stopDowningMusicArr containsObject:musicID]) {
//                [_downingMusicArr addObject:musicModel];
//            }
//        }
//    }
    
    //整理。麻烦
    [_stopDowningMusicArr removeAllObjects];
    for (DownMusicModel *musicModel in _downingMusicArr) {
        NSString *musicID = [NSString stringWithFormat:@"%@",musicModel.musicID];
        [_stopDowningMusicArr addObject:musicID];
    }
    
    [_tableView reloadData];
}

//增加的3个头部按钮 播放、批量、更多
- (UIView *)setTableHeaderViewWithIndex:(NSInteger)index
{
    UIView *bgView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 120*PERCEN)];
    bgView.backgroundColor = [UIColor clearColor];
    
    UIView *contentView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, bgView.width, 100*PERCEN)];
    contentView.backgroundColor = [UIColor whiteColor];
    [bgView addSubview:contentView];
    
    float itemWidth = 20*PERCEN;
    float btWidth = 1.*(bgView.width-(index+1)*itemWidth)/index;
    if (ISIPAD) {
        itemWidth = 44*PERCEN;
        btWidth = 540*PERCEN;
    }
    for (int i=0; i<index; i++) {
        UIButton *bt = [UIButton buttonWithType:UIButtonTypeCustom];
        bt.frame = CGRectMake(itemWidth+(btWidth+itemWidth)*i, 18*PERCEN, btWidth, 64*PERCEN);
        if (ISIPAD) {
            bt.left = (self.orientation==UIDeviceOrientationPortrait?(contentView.width-btWidth*index-itemWidth*(index-1))/2.:440*PERCEN)+(btWidth+44*PERCEN)*i;
        }
        bt.backgroundColor = [UIColor whiteColor];
        [bt setTitleColor:UIColorFromHex(0x333333) forState:UIControlStateNormal];
        bt.layer.cornerRadius = 6.f;
        bt.layer.masksToBounds = YES;
        bt.layer.borderColor = UIColorFromHex(0x999999).CGColor;
        bt.layer.borderWidth = 1;
        bt.tag = 1000+i;
        bt.titleLabel.font = [UIFont systemFontOfSize:13.];
        [bt addTarget:self action:@selector(onTapForMusicAction:) forControlEvents:UIControlEventTouchUpInside];
        [contentView addSubview:bt];
        
        if (i == 0) {
            [bt setTitle:@"全部开始" forState:UIControlStateNormal];
        }
        else if (i == 1) {
            [bt setTitle:@"批量操作" forState:UIControlStateNormal];
        }
        else if (i == 2) {
            [bt setTitle:@"更多" forState:UIControlStateNormal];
        }
    }
    
    return bgView;
}

#pragma mark - 跳转播放器
- (void)onSelectItemForWork
{
    [self onPlayMusic];
}

#pragma mark - 全部开始、批量、更多
- (void)onTapForMusicAction:(UIButton *)bt
{
    switch (bt.tag-1000) {
        case 0:
        {
            if ([bt.titleLabel.text isEqualToString:@"全部开始"]) {
                //全部开始
                _allCellStop = NO;
                if (_downingMusicArr.count > 0) {
                    //让新下载的任务继续进行下载
                    NSArray *msuicNArr = [[DownManager staredInstance]pauseAllMusic:NO];
                    if (msuicNArr.count > 0) {
                        //之前暂停推出程序的下载任务重新下载
                        for (DownMusicModel *musicModel in msuicNArr) {
                            
                            if ([musicModel.musicType intValue] >= 1 && [musicModel.musicType intValue] <= 4) {
                                //音频下载
                                NSString *audioName = [NSString stringWithFormat:@"%@.%@",musicModel.fileName,[[musicModel.url componentsSeparatedByString:@"."] lastObject]];
                                NSDictionary *dic = @{@"ID":musicModel.musicID,
                                                      @"AudioPath":[musicModel.url componentsSeparatedByString:MUSIC_PLAY_Url].lastObject,
                                                      @"AudioName":audioName,
                                                      @"ValueID":musicModel.musicType};
                                [[UserManager standerDefult]downLoadMusic:dic withRequestArr:@[]];
                            }
                            else if ([musicModel.musicType intValue] >= 5) {
                                NSDate *date = [NSDate date];
                                NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
                                [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
                                NSString *dateString = [formatter stringFromDate:date];
                                NSString *filePath = musicModel.url;
                                NSString *typePath = @"mp3";
                                if (![filePath isKindOfClass:[NSNull class]]) {
                                    typePath = [[filePath componentsSeparatedByString:@"."]lastObject];
                                    if (filePath.length > 0) {
                                        //头像
                                        NSString *FaceImg = musicModel.userPic;
                                        if ([FaceImg isKindOfClass:[NSNull class]]) {
                                            FaceImg = @"";
                                        }
                                        if (FaceImg.length > 0) {
                                            FaceImg = [NSString stringWithFormat:@"%@%@",MUSIC_PLAY_Url,FaceImg];
                                        }
                                        //背景
                                        NSString *CoverPath = musicModel.picUrl;
                                        if ([CoverPath isKindOfClass:[NSNull class]]) {
                                            CoverPath = @"";
                                        }
                                        if (CoverPath.length > 0) {
                                            CoverPath = [NSString stringWithFormat:@"%@%@",MUSIC_PLAY_Url,CoverPath];
                                        }
                                        [[DownManager staredInstance]downloadWithUrl:[NSString stringWithFormat:@"%@%@",MUSIC_PLAY_Url,filePath]
                                                                       withMusicName:[NSString stringWithFormat:@"%@.%@",musicModel.fileName,typePath]
                                                                          withUserID:[NSString stringWithFormat:@"%@",musicModel.userID]
                                                                         withMusicID:[NSString stringWithFormat:@"%@",musicModel.musicID]
                                                                         withContent:[NSString stringWithFormat:@"%@",musicModel.content]
                                                                       withMusicType:[NSString stringWithFormat:@"%@",musicModel.musicType]
                                                                          withPicUrl:CoverPath
                                                                            withDate:dateString
                                                                         withUserPic:FaceImg
                                                                        withUserNick:[NSString stringWithFormat:@"%@",musicModel.userNick]
                                                                            withSize:[NSString stringWithFormat:@"%@",musicModel.size]
                                                                        withProgress:nil withStats:nil];
                                    }
                                }
                            }
                        }
                    }

                }
                
                //播全部开始变成全部暂停
                [bt setTitle:@"全部暂停" forState:0];
                _allCellStop = DowningMusicStepType_ALLStart;
                [_tableView reloadData];
                
            } else {
                //播全部开始变成全部暂停
                [bt setTitle:@"全部开始" forState:0];
                _allCellStop = DowningMusicStepType_ALLStop;
                //全部暂停
                if (_downingMusicArr.count > 0) {
                    [[DownManager staredInstance]pauseAllMusic:YES];
                    [_stopDowningMusicArr removeAllObjects];
                    [_downingMusicArr removeAllObjects];
                    NSArray *sessionModels = [NSKeyedUnarchiver unarchiveObjectWithFile:DownloadDetailPath];
                    for (DownMusicModel *musicModel in sessionModels) {
                        NSString *musicID = [NSString stringWithFormat:@"%@",musicModel.musicID];
                        if (![_stopDowningMusicArr containsObject:musicID]) {
                            [_stopDowningMusicArr addObject:musicID];
                            [_downingMusicArr addObject:musicModel];
                        }
                    }
                    [_tableView reloadData];
                }
            }
        }
            break;
        case 1:
        {
            //批量
            self.isCompiling = !self.isCompiling;
            if (self.isCompiling) {
                //弹出批量框
                _tableView.height = self.view.height-_compileView.height;
                _compileView.top = _tableView.bottom;
                _compileView.hidden = NO;
                _currentMusicModel = nil;
                
            } else {
                //隐藏
                _tableView.height = self.view.height;
                _compileView.top = _tableView.bottom;
                _compileView.hidden = YES;
                self.isAllSelcting = NO; //不全选
                [_selectMusicArr removeAllObjects]; //删除所有选中的歌曲
                
            }
            //返回按钮改变
            [self onChangeBackButton:self.isCompiling];
            
            [_tableView reloadData];
        }
            break;
        case 2:
        {
            //更多
            //1.批量还原
            if (self.isCompiling) {
                UIButton *bt = (UIButton *)[self.view viewWithTag:1001];
                [self onTapForMusicAction:bt];
            }
            //2,显示
            SharePLayerView *show = [[SharePLayerView alloc]initWithFrame:CGRectZero withType:ShowPlayerType_Moer];
            show.delegate = self;
            show.orientation = self.orientation;
            [show onShowInWindow];
        }
            break;
            
        default:
            break;
    }
}

#pragma mark - 改变返回按钮样式
- (void)onChangeBackButton:(BOOL) compileStatus {
    if (compileStatus) {
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.frame = CGRectMake(0, 0, 60, 30);
        [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [btn.titleLabel setFont:[UIFont boldSystemFontOfSize:14.]];
        [btn setTitle:@"全选" forState:UIControlStateNormal];
        [btn setTitle:@"全选" forState:UIControlStateHighlighted];
        [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [btn setTitleEdgeInsets:UIEdgeInsetsMake(0, 0, 0, 25)];
        [btn addTarget:self action:@selector(onSelectTapAllMusicAction:) forControlEvents:UIControlEventTouchUpInside];
        
        [self setLeftBarItem:btn];
        [self setRightBarItems:nil];
    } else {
        [self setBackItem];
        
        [self setRightPlayerItem];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - 批量操作 取消、删除、收藏
- (void)onSelectItemForCancel:(MBSpaceCollectionCompileView *)view
{
    UIButton *bt = (UIButton *)[self.view viewWithTag:1001];
    [self onTapForMusicAction:bt];
}
- (void)onSelectItemForDelete:(MBSpaceCollectionCompileView *)view
{
    if (_selectMusicArr.count > 0) {
        NSMutableArray *newArr = [[NSMutableArray alloc]initWithArray:_selectMusicArr];
        for (DownMusicModel *model in newArr) {
            DownManager *manager = [DownManager staredInstance];
            if ([_stopDowningMusicArr containsObject:model.musicID]) {
                NSUInteger index = [_stopDowningMusicArr indexOfObject:model.musicID];
                [_downingMusicArr removeObject:model];
                [_stopDowningMusicArr removeObject:model.musicID];
                [_tableView deleteRowsAtIndexPaths:@[[NSIndexPath indexPathForItem:index inSection:0]] withRowAnimation:UITableViewRowAnimationFade];
            }
           
            [manager deleteFile:model];
            
            //同步
            NSString *filePath = [MusicCachesDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.mp3",model.fileName]];
            NSFileManager *fileManager = [NSFileManager defaultManager];
            if ([fileManager fileExistsAtPath:filePath]) {
                [fileManager removeItemAtPath:filePath error:NULL];
            }
        }
    }
    
    [_selectMusicArr removeAllObjects];
    if (_downingMusicArr.count == 0) {
        //已下载歌曲删除完
        UIButton *bt = (UIButton *)[self.view viewWithTag:1001];
        [self onTapForMusicAction:bt];
    }
}
- (void)onSelectItemForNoCollection:(MBSpaceCollectionCompileView *)view
{
    
}

#pragma mark - 勾选一首歌曲
- (void)onSelectItemForGouXuanWithValue:(DownMusicModel *)model WithSelect:(BOOL)isSelect WithView:(MBSpaceDowningAllMusicCell *)view
{
    //数据保存
    NSLog(@"数据是否需要保存:%d",isSelect);
    if (isSelect) {
        //保存
        [_selectMusicArr addObject:model];
    } else {
        //删除
        if ([_selectMusicArr containsObject:model]) {
            [_selectMusicArr removeObject:model];
        }
    }
    
    //删除、收藏是否可选中
    [_compileView onUpdateDataForDelegateAndCollection:(_selectMusicArr.count > 0 ? YES : NO)];
    
    if (_selectMusicArr.count != _downingMusicArr.count) {
        //不相等 显示全选
        [self onChangeBackButton:YES];
    }
}


#pragma mark - 全选
- (void)onSelectAllMusicAction:(BOOL)isAllSelect
{
    self.isAllSelcting = isAllSelect;
    
    //测试
    [_selectMusicArr removeAllObjects];
    if (isAllSelect) {
        [_selectMusicArr addObjectsFromArray:_downingMusicArr];
    }
    
    //删除、收藏是否可选中
    [_compileView onUpdateDataForDelegateAndCollection:(_selectMusicArr.count > 0 ? YES : NO)];
    
    [_tableView reloadData];
}

//全选
- (void)onSelectTapAllMusicAction:(UIButton *)bt
{
    bt.selected = !bt.selected;
    if (bt.selected) {
        [bt setTitle:@"全不选" forState:UIControlStateNormal];
        [bt setTitle:@"全不选" forState:UIControlStateHighlighted];
        [bt setTitleEdgeInsets:UIEdgeInsetsMake(0, 0, 0, 15)];
    } else {
        [bt setTitle:@"全选" forState:UIControlStateNormal];
        [bt setTitle:@"全选" forState:UIControlStateHighlighted];
        [bt setTitleEdgeInsets:UIEdgeInsetsMake(0, 0, 0, 25)];
    }
    [self onSelectAllMusicAction:bt.selected];
}

#pragma mark - 更多操作 添加歌曲、播放、分享、取消收藏、下载
//添加歌曲
- (void)onSelctItemForMoreAddMusic:(SharePLayerView *)view
{
//    MBSpaceAddMusicViewController *addMusic = [[MBSpaceAddMusicViewController alloc]init];
//    addMusic.type = MBSpaceAddMusicType_SetAlbum;
//    addMusic.albumName = @"分类";
//    [self.navigationController pushViewController:addMusic animated:YES];
}

//每个歌曲更多操作
- (void)onSelectItemForMoewWithValue:(DownMusicModel *)model withView:(MBSpaceDowningAllMusicCell *)view
{
    if (model) {
        _currentMusicModel = model;
        
        SharePLayerView *show = [[SharePLayerView alloc]initWithFrame:CGRectZero withType:ShowPlayerType_DownMusic];
        show.delegate = self;
        show.orientation = self.orientation;
        [show onShowInWindow];
    }
}

//播放
- (void)onSelctItemForMorePlayMusic:(SharePLayerView *)view
{
    if (!_currentMusicModel) {
        //第一次
        [[UserManager standerDefult]playMusicWithMusicArray:_downingMusicArr withCurrentIndex:0 withMusicPlayType:_musicPlayType];
    } else if ([_stopDowningMusicArr containsObject:_currentMusicModel.musicID]) {
        int index = (int)[_downingMusicArr indexOfObject:_currentMusicModel.musicID];
        //当前页面播放
        [[UserManager standerDefult]playMusicWithMusicArray:_downingMusicArr withCurrentIndex:index withMusicPlayType:_musicPlayType];
    }
}

//删除
- (void)onSelctItemForMoreDeleteMusic:(SharePLayerView *)view
{
    if (_downingMusicArr.count > 0 && [_stopDowningMusicArr containsObject:_currentMusicModel.musicID]) {
        NSUInteger index = [_stopDowningMusicArr indexOfObject:_currentMusicModel.musicID];
        DownManager *manager = [DownManager staredInstance];
        [_downingMusicArr removeObject:_currentMusicModel];
        [_stopDowningMusicArr removeObject:_currentMusicModel.musicID];
        [_tableView deleteRowsAtIndexPaths:@[[NSIndexPath indexPathForItem:index inSection:0]] withRowAnimation:UITableViewRowAnimationFade];
        [manager deleteFile:_currentMusicModel];
        _currentMusicModel = nil;
    }

}

#pragma mark - UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _downingMusicArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //歌曲
    static NSString *cellID = @"Downing_Music_Cell";
    MBSpaceDowningAllMusicCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    if (!cell) {
        cell = [[MBSpaceDowningAllMusicCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.delegate = self;
        [DownManager staredInstance].delegate = self;
    }
    //是否隐藏更多按钮
    cell.isHideMoewBt = NO;
    [cell onCompileCellForLayout:self.isCompiling WithAllSelct:self.isAllSelcting];
    cell.orientation = self.orientation;
    
    //value
    if (_allCellStop == DowningMusicStepType_ALLStop) {
        cell.isAllStop = YES;
    } else {
        cell.isAllStop = NO;
    }
    if (_downingMusicArr.count > indexPath.row) {
        DownMusicModel *model = [_downingMusicArr objectAtIndex:indexPath.row];
        cell.musicDownModel = model;
        if (_selectMusicArr.count > 0) {
            if ([_stopDowningMusicArr containsObject:model.musicID]) {
                cell.isSelect = YES;
            } else {
                cell.isSelect = NO;
            }
        }
    }
    
    return cell;
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 130*PERCEN;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"*******");
    if (!self.isCompiling) {
        
        if ([UserManager standerDefult].musicPlayType != _musicPlayType) {
            //第一次
            [[UserManager standerDefult]playMusicWithMusicArray:_downingMusicArr withCurrentIndex:indexPath.row withMusicPlayType:_musicPlayType];
        }
        else if ([UserManager standerDefult].selectMusicIndex != indexPath.row) {
            //当前页面播放
            [[UserManager standerDefult]playMusicWithMusicArray:_downingMusicArr withCurrentIndex:indexPath.row withMusicPlayType:_musicPlayType];
        } else {
            //2次点击进入播放页面
            if ([UserManager standerDefult].musicArr.count > 0) {
                //歌曲列表没歌曲 无需进入
                UserManager *manager = [UserManager standerDefult];
                [manager setSelectMusicIndex:indexPath.row];
                if (manager.audioPlayerType != AudioPLayerType_YinPin) {
                    [manager setIsPlaying:NO];
                    [manager setAudioPlayerType:AudioPLayerType_YinPin];
                } else {
                    [manager setIsPlaying:YES];
                }
//                if (ISIPAD) {
//                    MBSongDetailForIController*song=[[MBSongDetailForIController alloc]init];
//                    [self.navigationController pushViewController:song animated:YES];
//                }
                if (ISIPAD) {
                    MBSongDetailForIpadController*song=[[MBSongDetailForIpadController alloc]init];
                    [self.navigationController pushViewController:song animated:YES];
                    return;
                }
                
                MBSongDetailController *song = [[MBSongDetailController alloc]init];
                [self.navigationController pushViewController:song animated:YES];
            }
        }
        
        
    }
    else {
        //编辑状态就选中勾选
        MBSpaceDowningAllMusicCell *cell = (MBSpaceDowningAllMusicCell *)[tableView cellForRowAtIndexPath:indexPath];
        if ([cell isKindOfClass:[MBSpaceDowningAllMusicCell class]]) {
            [cell onGouXuanToSelectAction:cell.selectBt];
        }
    }
}

#pragma mark - 下载回掉
- (void)downloadResponse:(DownMusicModel *)musicModel
{
    if (_downingMusicArr.count > 0) {
        // 取到对应的cell上的model
        if ([_stopDowningMusicArr containsObject:[NSString stringWithFormat:@"%@",musicModel.musicID]]) {
            
            if (_isShowAllStop == NO) {
                _isShowAllStop = YES;
                
                UIButton *bt = (UIButton *)[self.view viewWithTag:1000];
                [bt setTitle:@"全部暂停" forState:UIControlStateNormal];
            }
            
            NSInteger index = [_stopDowningMusicArr indexOfObject:musicModel.musicID];
            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:index inSection:0];
            __block MBSpaceDowningAllMusicCell *cell = [_tableView cellForRowAtIndexPath:indexPath];
            __weak typeof(self) weakSelf = self;
            musicModel.progressBlock = ^(CGFloat progress, NSString *speed, NSString *remainingTime, NSString *writtenSize, NSString *totalSize) {
                dispatch_async(dispatch_get_main_queue(), ^{

                    [cell layoutDataWithSize:speed withProgress:progress];
                });
            };
            __weak typeof(musicModel) weakModel = musicModel;
            musicModel.stateBlock = ^(DownMusicState state){
                dispatch_async(dispatch_get_main_queue(), ^{
                    // 更新数据源
                    if (state == DownMusicState_Completed) {
                        NSLog(@"****下载完毕");
                        [weakSelf onDownedMusicWithIndex:weakModel];
                    }

                });
            };
        }
    }

}

- (void)onDownedMusicWithIndex:(DownMusicModel *)musicModel
{
    if (_downingMusicArr.count == 0) return;
    if (![_stopDowningMusicArr containsObject:musicModel.musicID]) return;

    if (_selectMusicArr.count > 0) {
        if (![_stopDowningMusicArr containsObject:musicModel.musicID]) {
            [_selectMusicArr removeObject:musicModel];
        }
    }
    
    if ([_stopDowningMusicArr containsObject:musicModel.musicID]) {
        NSUInteger index = [_stopDowningMusicArr indexOfObject:musicModel.musicID];
        [_downingMusicArr removeObjectAtIndex:index];
        [_stopDowningMusicArr removeObjectAtIndex:index];
        
        [_tableView deleteRowsAtIndexPaths:@[[NSIndexPath indexPathForItem:index inSection:0]] withRowAnimation:UITableViewRowAnimationFade];
    }
    [_tableView reloadData];
}

@end
